package datastructure.stackAndQueue;

public class ArrayStack implements Stack{

	private static  final int DEFAULT_SIZE = 10;	//�����Ĭ�ϴ�С
	private int top ;	//ָ��ָ��ջ��Ԫ�ص��Ϸ�
	private Object[] array;
	
	public ArrayStack(){	//Ĭ�ϴ�С��ջ
		array = new Object[DEFAULT_SIZE];
		top = 0;
	}
	public ArrayStack(int size){	//ָ����С��ջ
		array = new Object[size];
		top = 0;
	}
	
	@Override
	public void clear() {
		for(int i=0;i<top;i++)
			array[i] = null;
		top = 0;
	}

	@Override
	public boolean isEmpty() {
		return top==0;
	}

	@Override
	public Object peek() {
		if(top==0)
			try {
				throw new IllegalStackException();
			} catch (IllegalStackException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return array[top-1];	
	}

	@Override
	public Object pop() {
		if(top==0){
			try {
				throw new IllegalStackException();
			} catch (IllegalStackException e) {
				e.printStackTrace();
			}
		}
		Object val = array[--top];
		array[top] = null;
		return val;
	}

	@Override
	public void push(Object val) {
		if(top==array.length)
			expand();
		array[top++] = val;
	}

	@Override
	public int size() {
		return top;
	}
	

	//���鳤�ȼӱ�
	private void expand(){
		Object[] newArray = new Object[2*array.length];
		for(int i=0;i<array.length;i++){
			newArray[i] = array[i];
		}
		array = newArray;
	}
	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer("[");
		for(int i=0;i<top;i++){
			if(i>0)
				buf.append(",");
			buf.append(array[i]);
		}
		buf.append("]");
		return buf.toString();
	}
	
	
	
}
